package com.cyq.blog.intercepter;

import com.cyq.blog.entity.Admin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * AdminIntercepter class
 *
 * @author chenyeqing
 * @date 2021/5/14
 */
@Slf4j
@Component
public class AdminIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("URL=>" + request.getRequestURL());
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (ObjectUtils.isEmpty(admin)) {
            request.getSession().setAttribute("errorMsg", "未登录，被拦截，请登录");
            response.sendRedirect("/admin/login");
            return false;
        } else {
            request.getSession().removeAttribute("errorMsg");
            request.getSession().setAttribute("admin", admin);
            return true;
        }
    }
}
